package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域资源共享过滤器:
 *      用于告知浏览器,本服务器返回的所有资源允许跨域展示
 */
//@WebFilter("/*")
public class CorsFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 获取请求来源
        /*String origin = request.getHeader("Origin");
        System.out.println("请求来源为: "+origin);
        response.setHeader("Access-Control-Allow-Origin", origin);*/
        // TODO:设置允许跨域 这行设置可以解决跨域的简单请求
        //表示允许请求时的origin值(发出请求的网址)
        response.setHeader("Access-Control-Allow-Origin", "*");
        // TODO: 非简单请求 "预检"
        /*
            # 预检时,告诉浏览器允许的请求方式有哪些
            Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
            # 预检时,告诉浏览器允许携带的请求头有哪些
            Access-Control-Allow-Headers:content-type
            # 预检时,告诉浏览器允许的起源有哪些
            Access-Control-Allow-Origin: *
            # 预检完成后,告诉浏览器本次预检生效的时长
            Access-Control-Max-Age: 3600
        */
        // TODO:预检时,告诉浏览器允许的请求方式有哪些
        //response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Methods", "*");
        // TODO:预检时,告诉浏览器允许携带的请求头有哪些
        response.setHeader("Access-Control-Allow-Headers", "*");
        //如果需要携带多个请求头(包括自定义的请求头),可以加
        // response.setHeader("Access-Control-Allow-Headers", "content-type,authorization");
        // TODO:# 预检完成后,告诉浏览器本次预检生效的时长 单位是秒
        response.setHeader("Access-Control-Max-Age", "3600");

        // 放行
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
